from eim.tools.dbtool import DBTool
from eim.tools.searchtool import MatchLogic,PartnerRS,SearchCondition,SearchConditionList
from eim.DataBasModals.mode import t_powers,t_operate,t_mastnetcomlog,t_netanalysisrule
from eim.result.page_result import PageResult
from eim.result.simple_result import SimpleResult
from flask import current_app
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func,select,update,delete,text,or_,and_,insert,join
from sqlalchemy.engine import LegacyRow,Connection,CursorResult
from eim.tools.searchtool import SearchCondition,SearchConditionList,MatchLogic,PartnerRS,GlobalSearch

class DocTypeService:
    """
    文件类别操作类
    """
    def __init__(self,db:SQLAlchemy):
        self.db = db
    
    
    # 获取指定父编码的上层类别编码
    def _getParentDir(self,pcode:str,precode:list=[])->str:
        """
        获取指定父编码的上层类别编码
        Keyword arguments:
        pcode -- 上层类别编码
        precode -- 上层结果
        Return: 返回指定父级编码的所有父编码
        """
        qry = GlobalSearch(self.db)
        selist = SearchConditionList()
        se = SearchCondition("code",MatchLogic.from_Name("EQ"),pcode)
        selist.appendCondition(PartnerRS.from_name("AND"),se)
        res = qry.getTableData("doctype",["code","pcode"],selist)
        precode.append(pcode)
        
        if len(res)>0:
            code = res[0]["pcode"]
            self._getParentDir(code,precode)
        
        
    # 校验父级编码的正确性   
    def checkParent(self,pcode:str)->bool:
        """
        校验父编码是否正确    
        Keyword arguments:
        argument -- 待校验的父级编码
        Return: 返回校验结果
        """
        try:
            qry = GlobalSearch(self.db)
            selist = SearchConditionList()
            se = SearchCondition("code",MatchLogic.from_Name("EQ"),pcode)
            selist.appendCondition(PartnerRS.from_name("AND"),se)
            res = qry.getTableData("doctype",["code"],selist)
            if len(res)>0:
                return True
            else:
                return False
        except Exception as es:
            return False

    #校验目标文档是否为叶子节点
    def isLeafLevel(self,pcode:str)->bool:
        """
        校验目标文档类别编码是否为叶子节点  
        
        Keyword arguments:
        argument -- 目标文档类别编号
        Return: 返回校验结果
        """
        try:
            qry = GlobalSearch(self.db)
            selist = SearchConditionList()
            se = SearchCondition("code",MatchLogic.from_Name("EQ"),pcode)
            selist.appendCondition(PartnerRS.from_name("AND"),se)
            res = qry.getTableData("doctype",["isleaf"],selist) 
            
            if pcode=='': #如果父级类别编码为空则为顶层类别
                return False
            
            if len(res)<=0: #如果不能存在以指定父级编码为编码的记录则返回true
                return True
            else:
                isleaf = res[0]["isleaf"]
                if isleaf=='00':
                    return False
                else:
                    return True
        except Exception as es:
            raise es     

    # 获取指定父级编码的路径字符串
    def getParentPath(self,parentCode:str):
        """
        获取指定编码的层次编码
        
        Keyword arguments:
        argument -- 父编码
        Return: 返回路径名称和层次
        """
        plist=[]
        self._getParentDir(parentCode,plist)
        plist.reverse()
        del(plist[0])
        ppath="./docs"
        for d in plist:
            if d!="":
                ppath=f"{ppath}/{d}"
        ppath=f"{ppath}/"
        return ppath,len(plist) 
    
    # 获取指定编码的子类别
    def getTypeChildren(self,pcode:str,types:list)->list:
        """
        返回指定编码的子节点列表
        
        Keyword arguments:
        argument -- 编码
        Return: 子节点
        """
        res:list=[]
        for t in types:
            if t["pcode"]==pcode:
                res.append(t)
        
        return res


    def makeMenuTree(self,types,pnode):
        """
        构建类别菜单树

        Args:
            types (_type_): 所有类别列表 
            pnode (_type_): 顶层节点
        """
        for t in types:
            if t["pcode"]==pnode["code"]:
                curnode={}
                curnode["code"]=t["code"]
                curnode["text"]=t["name"]
                curnode["opened"]='true'
                curnode["isleaf"]=t["isleaf"]
                if(t["isleaf"]=="01"):
                    curnode["icon"]="fa fa-envira"
                curnode["children"]=[]
                children=self.getTypeChildren(curnode["code"],types)
                if len(children)>0:
                    self.makeMenuTree(types,curnode)
                pnode["children"].append(curnode)        
        return pnode
            
            
            
            
